package digui;

 class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }
public class Test2 {
     //题目: 力扣21题 合并两个有序链表
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        //直接用递归  解决  重复子问题
        //每次就是拿出较小的那个节点出来  再在剩下的两个链表的节点进行合并

        if(list1 == null) {
            return list2;
        }else if(list2 == null) {
            return list1;
        }else if(list1.val < list2.val) {
            list1.next = mergeTwoLists(list1.next,list2);
            return list1;
        }else {
            list2.next = mergeTwoLists(list1,list2.next);
            return list2;
        }
    }

    //循环实现
    public ListNode mergeTwoLists1(ListNode list1, ListNode list2) {
        ListNode newHead = new ListNode(0);
        ListNode tmp = newHead;
        while(list1 != null&&list2 != null){
            if(list1.val<list2.val){
                tmp.next = list1;
                list1 = list1.next;
                tmp = tmp.next;
            }else{
                tmp.next = list2;
                list2 = list2.next;
                tmp = tmp.next;
            }
        }
        if(list1 != null){
            tmp.next = list1;

        }
        if(list2 != null){
            tmp.next = list2;
        }
        return newHead.next;
    }
    public static void main(String[] args) {

    }
}
